package com.hmall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.ObjectUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
@Import(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private AuthProperties authProperties;

    @Autowired
    private JwtTool jwtTool;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // TODO 1、获取请求对象
        ServerHttpRequest request = exchange.getRequest();

        // TODO 2、获取请求路径
        String path = request.getPath().toString();
        // 路径是否在白名单内
        for (String excludePath : authProperties.getExcludePaths()) {
            //请求路径如果满足白名单规则,直接放行
            if (new AntPathMatcher().match(excludePath, path)) {
                return chain.filter(exchange);
            }
        }

        // TODO 3、从请求头中获取token,解析并校验token, 如果解析失败, 直接返回401状态码
        String token = request.getHeaders().getFirst("Authorization");
        try {
            Long userId = jwtTool.parseToken(token);
            // 解析出的结果不正确，直接返回401
            if (ObjectUtil.isEmpty(userId)) {
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }

            // TODO 4、将解析出的用户id添加到请求头中，传递给后续微服务
            ServerWebExchange ex = exchange.mutate().request(b -> b.header("user-info", userId.toString())).build();

            // TODO 5、放行
            return chain.filter(ex);
        } catch (Exception e) {
            // 解析失败，直接返回401
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }

    @Override
    // 这个返回值用于控制当前过滤器在过滤器链中执行的优先级, 数字越小 优先级越高
    public int getOrder() {
        return 0;
    }
}
